<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <search ref="search"  :config="searchConfig" @search="search" @getHeight="getHeight"/>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary">新增</a-button>
      <a-button type="primary"  @click="startorstop('009')">删除</a-button>
      <a-button type="primary"  @click="startorstop('003')">停用</a-button>
      <a-button @click="" type="primary"  >导出</a-button>
      <a-button type="primary"  @click="startorstop('009')">日志</a-button>
      <!--      <a-button @click="handleEnable" type="primary">启用</a-button>-->
      <!--      <a-button @click="handleDisable" type="primary">停用</a-button>-->
      <!--      <a-button @click="handleTerminal" type="primary">关联终端</a-button>-->

<!--      <a-button type="primary" icon="download" @click="downExportXls('dmsProductPrice_service')">导出</a-button>-->
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
      <!--        <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <!-- 高级查询区域 -->
      <!--      <j-super-query :fieldList="fieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <!--      <a-dropdown v-if="selectedRowKeys.length > 0">-->
      <!--        <a-menu slot="overlay">-->
      <!--          <a-menu-item key="1" @click="batchDel">-->
      <!--            <a-icon type="delete"/>-->
      <!--            删除-->
      <!--          </a-menu-item>-->
      <!--        </a-menu>-->
      <!--        <a-button style="margin-left: 8px"> 批量操作-->
      <!--          <a-icon type="down"/>-->
      <!--        </a-button>-->
      <!--      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
<!--      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">-->
<!--        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{-->
<!--          selectedRowKeys.length-->
<!--        }}</a>项-->
<!--        <a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
<!--        <span style="float:right;">-->
<!--          <a @click="loadData()"><a-icon type="sync"/>刷新</a>-->
<!--          <a-divider type="vertical"/>-->
<!--          <a-popover title="自定义列" trigger="click" placement="leftBottom">-->
<!--            <template slot="content">-->
<!--              <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">-->
<!--                <a-row>-->
<!--                  <template v-for="(item,index) in defColumns">-->
<!--                    <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">-->
<!--                        <a-col :span="12"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>-->
<!--                    </template>-->
<!--                  </template>-->
<!--                </a-row>-->
<!--              </a-checkbox-group>-->
<!--            </template>-->
<!--            <a><a-icon type="setting"/>设置</a>-->
<!--          </a-popover>-->
<!--        </span>-->
<!--      </div>-->

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="{x:1500,y:pageHeight-seachHeight-275}"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :customRow="onClickRow"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">


        <!--        <template slot="avatar" slot-scope="text, record, index">-->
        <!--          <div class="anty-img-wrap">-->
        <!--            <a-avatar shape="square" :src="record.avatar" icon="user"/>-->
        <!--          </div>-->
        <!--        </template>-->
        <!--        <div slot="isActiveStatus" slot-scope="text,recode">-->
        <!--          {{ text|isActiveStatus }}-->
        <!--        </div>-->
        <!--        <div slot="filterCustType" slot-scope="text,recode">-->
        <!--        {{ text|filterCustType }}-->
        <!--    </div>-->
        <!--        设置图标-->
        <!--        <a-icon slot="filterIcon" type='setting' :style="{ fontSize:'16px',color:  '#108ee9' }" />-->
        <div slot="productName" slot-scope="text,record">
          <a @click="handleDetail(record)">{{text}}</a>
        </div>
        <div slot="updateStatus" slot-scope="text,record">
          <a-switch  :checked="record.status" size="small"  @change="handleFixSiderbar" />
        </div>
        <div slot="filterDropdown">
          <a-card>
            <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
              <a-row>
                <template v-for="(item,index) in defColumns">
                  <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                    <a-col :span="12">
                      <a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox>
                    </a-col>
                  </template>
                </template>
              </a-row>
            </a-checkbox-group>
          </a-card>
        </div>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down"/></a>
            <a-menu slot="overlay">

              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
<!--    <materialModal ref="modalForm" @ok="modalFormOk"></materialModal>-->
    <form-add-edit ref='popupForm' @ok='modelFormOkss'></form-add-edit>
  </a-card>
</template>

<script>
  import FormAddEdit from '@comp/view/base-crud/form/FormAddEdit'
import JSuperQuery from '@/components/cn-form/JSuperQuery.vue'
import JInput from '@/components/cn-form/JInput.vue'
import { initDictOptions, filterDictText, filterDictTextByCache } from '@/components/dict/CnDictSelectUtil'
import { PageListMixin } from '@/mixins/PageListMixin'
import Vue from 'vue'
import { filterObj } from '@/utils/util'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import { postAction } from '../../../api/manage'
// import materialModal from './modules/materialModal'
import { getAction } from '@/api/manage'
import search from '@comp/view/base-crud/search/Search'

//高级查询modal需要参数

export default {
  name: 'material',
  mixins: [PageListMixin],
  components: {
    JSuperQuery,
    JInput,
    JTreeSelect,FormAddEdit,
    // materialModal,
    search
  },
  // priceAdd
  data() {
    return {
      description: '经销商可购清单',
      //字典数组缓存
      sexDictOptions: [],
      importExcelUrl: `${window._CONFIG['domianURL']}/test/cn-formDemo/importExcel`,
      config : {
        title: '编辑配置',
        width: 800,
        addOrUpdateUrl: `${window._CONFIG['domianConfigURL']}/genDataInfoController/saveOrUpdate`,  //审核地址
        method: 'post',
        divider:{
          name:'基础信息',
          location:'left',
        },
        list: [
          {
            label: '提货点编号',
            type: 'input',
            name: 'name',  // 后台接受字段
            placeholder: '',
            check: { rules: [{ required: true, message: '请填写提货点编号',whitespace:true}] },
            md:12,
          },
          // {
          //   label: '所属模块',
          //   type: 'j-select',
          //   name: 'module',  // 后台接受字段
          //   placeholder: '请选择所属模块',
          //   dictCode:"module",
          //   check: { rules: [{ required: true, message: '请选择所属模块',whitespace:true}] }
          // },
          {
            label: '提货点名称',
            type: 'input',
            name: 'bussiPackage',  // 后台接受字段
            placeholder: '',

            md:12,

            // check: { rules: [{ required: true, message: '请输入package路径',whitespace:true }] }
          },
          {
            label: '提货点编类型',
            type: 'j-select',
            name: 'configName',  // 后台接受字段
            placeholder: '',
            dictCode:'',
            md:12,
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '别名代码',
            type: 'j-select',
            name: 'configName',  // 后台接受字段
            placeholder: '',
            dictCode:'',
            md:12,
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '行政区域',
            type: 'j-select',
            name: 'configName',  // 后台接受字段
            placeholder: '',
            dictCode:'',
            md:12,
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '街道',
            type: 'j-select',
            name: 'configName',  // 后台接受字段
            placeholder: '',
            dictCode:'',
            md:12,
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '状态',
            type: 'a-select',
            name: 'configName',  // 后台接受字段
            placeholder: '',
            md:12,
            option:[{
              name:'启用',
              value:1
            },{
              name: '停用',
              value: 0
            }],
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '工厂',
            type: 'j-select',
            name: 'configName',  // 后台接受字段
            placeholder: '',
            dictCode:'',
            md:12,
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '满足率（%）',
            type: 'input-number',
            name: 'configName',  // 后台接受字段
            placeholder: '',
            dictCode:'',
            min:'0',
            mix:'100',
            md:12,
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '是否预约',
            type: 'a-select',
            name: 'configName',  // 后台接受字段
            placeholder: '',
            md:12,
            option:[{
              name:'是',
              value:'009'
            },{
              name:'否',
              value:'003'
            }],
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '是否自动寻仓',
            type: 'a-select',
            name: 'configName',  // 后台接受字段
            placeholder: '',
            md:12,
            option:[{
              name:'是',
              value:'009'
            },{
              name:'否',
              value:'003'
            }],
            // check: { rules: [{ required: true, message: '数据库信息配置',whitespace:true }] }
          },
          {
            label: '备注',
            type: 'textarea',
            placeholder: '',
            labelCol: {
              xs: { span: 24 },
              sm: { span: 3 }
            },
            name: 'remarks'  // 后台接受字段
          }
        ],

      },
      searchConfig:[
        {
          // label:'订单编号',
          type:'input',
          name:'matnr',
          placeholder:'提货点',
        },
        {
          type:'input',
          name:'maktx',
          placeholder:'产品编号',
        },
        {
          type:'input',
          name:'maktx',
          placeholder:'产品名称',
        },
        {

          type:'a-select',
          name:'status',
          option:[{
            name:'启用',
            value:1
          },{
            name: '停用',
            value: 0
          }],
          placeholder:'请选择状态',
        }],
      //表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义  表格改这儿
      defColumns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料编号',
          align: 'center',
          dataIndex: 'matnr'
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'maktx'
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'model'
        },
        // {
        //   title: '基本单位',
        //   align: 'center',
        //   dataIndex: 'meins'
        // },
        {
          title: '基本单位',
          align: 'center',
          dataIndex: 'meinst'
        },
        // {
        //   title: '销售单位',
        //   align: 'center',
        //   dataIndex: 'vrkme'
        // },
        {
          title: '销售单位',
          align: 'center',
          dataIndex: 'vrkmet'
        },
        {
          title: '当前单位数量',
          align: 'center',
          dataIndex: 'umren'
        },
        {
          title: '单位换算系数',
          align: 'center',
          dataIndex: 'umrez'
        },
        {
          title: '创建时间',
          align: 'center',
          dataIndex: 'createDate',
          customRender: (t, r, dex) => {
            return r.createDate + r.createDateTime
          }
        },
        {
          title: '最近更新人',
          align: 'center',
          dataIndex: 'updateName',
          ellipsis: true
        },
        {
          title: '最近更新时间',
          align: 'center',
          dataIndex: 'updateDate',
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          fixed: 'right',
          width: 120,
          scopedSlots: {
            // filterIcon: 'filterIcon',
            customRender: 'updateStatus'
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            // filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }
      ],
      url: {
        list: window._CONFIG['domianURL'] + '/material/findPageList',
        detail: window._CONFIG['domianURL'] + '/material/getInfo',
        delete: window._CONFIG['domianURL'] + '/material/deleteById',
        startOrStopUrl: window._CONFIG['domianURL'] + "/material/startOrStop",
        deleteBatch: '/test/cn-formDemo/deleteBatch',
        exportXlsUrl: '/test/cn-formDemo/exportXls'

      }

    }
  },
  methods: {
    startorstop: function(status) {
      if (!this.url.startOrStopUrl) {
        this.$message.error("请设置url启用停用!")
        return;
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');

      } else {
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        this.$confirm({
          title: "确认修改",
          content: "是否修改选中数据?",
          onOk: function () {
            that.loading = true;
            getAction(that.url.startOrStopUrl, {ids: ids, status: status}).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.loadData();
                that.onClearSelected();
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.loading = false;
            });
          }
        });
      }
    },
    selectCusttype(value) {
      this.$set(this.queryParam, 'custType', value)
    },

    handleAdd() {

      // let newDate = formatDateYmd(new Date().getTime())
      // ...this.selectionRows, startDate: newDate, endDate: newDate
      this.$refs.popupForm.edit({}, this.config)
      this.$refs.popupForm.disableSubmit = false

    },
    handleEdit:async function(row) {
      // let option=[]
      // let res = await getAction(window._CONFIG['domianConfigURL'] + '/genDataConfigController/getInfo',{id:row.id})
      // if(res.success){
      //   option = res.result.map(item=>{
      //     return {
      //       name:item.name,
      //       value:item.code
      //     }
      //   })
      // }else {
      //   this.$message.error(res.message)
      // }



      // let newDate = formatDateYmd(new Date().getTime())
      // ...this.selectionRows, startDate: newDate, endDate: newDate
      this.$refs.popupForm.edit(row,  this.config)
      this.$refs.popupForm.disableSubmit = false
    },
    getQueryParams() {
      //高级查询器
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      delete param.birthdayRange //范围参数不传递后台
      return filterObj(param)
    },
    // initDictConfig() {
    //   console.log("--我才是真的方法!--")
    //初始化字典 - 性别
    // initDictOptions('sex').then((res) => {
    //   if (res.success) {
    //     this.sexDictOptions = res.result;
    //   }
    // });
    // },
    //跳转单据页面
    jump() {
      this.$notification.success('跳转 ： jump')
    },
    onBirthdayChange: function(value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.birthday_begin = dateString[0]
      this.queryParam.birthday_end = dateString[1]
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function(item, i, array) {
          allSettingColumns.push(item.dataIndex)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    }
  },
  created() {
    this.initColumns()
  }

}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>